<template>
  <div class="workflow-task">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="单据类型">
            <el-select v-model="searchForm.billType" placeholder="请选择单据类型" clearable>
              <el-option label="生产任务" value="production_task" />
              <el-option label="采购订单" value="purchase_order" />
              <el-option label="财务单据" value="finance_bill" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务状态">
            <el-select v-model="searchForm.status" placeholder="请选择任务状态" clearable>
              <el-option label="待办" :value="0" />
              <el-option label="已办" :value="1" />
              <el-option label="已发" :value="2" />
              <el-option label="撤回" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleStartWorkflow">启动工作流</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="id" label="任务ID" width="80" />
        <el-table-column prop="processId" label="流程ID" width="80" />
        <el-table-column prop="nodeId" label="节点ID" width="80" />
        <el-table-column prop="billType" label="单据类型">
          <template #default="scope">
            <el-tag v-if="scope.row.billType === 'production_task'" type="success">生产任务</el-tag>
            <el-tag v-else-if="scope.row.billType === 'purchase_order'" type="warning">采购订单</el-tag>
            <el-tag v-else-if="scope.row.billType === 'finance_bill'" type="danger">财务单据</el-tag>
            <el-tag v-else type="info">{{ scope.row.billType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="billId" label="单据ID" width="100" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">待办</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">已办</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="info">已发</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="danger">撤回</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assigneeId" label="处理人ID" width="100" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status === 0" type="success" size="small" @click="handleApprove(scope.row)">审批</el-button>
            <el-button v-if="scope.row.status === 0" type="danger" size="small" @click="handleRevoke(scope.row)">撤回</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 启动工作流对话框 -->
    <el-dialog v-model="startDialogVisible" title="启动工作流" width="500px">
      <el-form :model="startForm" :rules="startRules" ref="startFormRef" label-width="100px">
        <el-form-item label="流程ID" prop="processId">
          <el-input v-model="startForm.processId" placeholder="请输入流程ID" type="number" />
        </el-form-item>
        <el-form-item label="单据类型" prop="billType">
          <el-select v-model="startForm.billType" placeholder="请选择单据类型">
            <el-option label="生产任务" value="production_task" />
            <el-option label="采购订单" value="purchase_order" />
            <el-option label="财务单据" value="finance_bill" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据ID" prop="billId">
          <el-input v-model="startForm.billId" placeholder="请输入单据ID" type="number" />
        </el-form-item>
        <el-form-item label="启动人ID" prop="userId">
          <el-input v-model="startForm.userId" placeholder="请输入启动人ID" type="number" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="startDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStartSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog v-model="approveDialogVisible" title="任务审批" width="500px">
      <el-form :model="approveForm" :rules="approveRules" ref="approveFormRef" label-width="100px">
        <el-form-item label="操作类型" prop="action">
          <el-radio-group v-model="approveForm.action">
            <el-radio value="approve">同意</el-radio>
            <el-radio value="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="remark">
          <el-input v-model="approveForm.remark" type="textarea" placeholder="请输入审批意见" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="approveForm.userId" placeholder="请输入用户ID" type="number" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 撤回对话框 -->
    <el-dialog v-model="revokeDialogVisible" title="撤回任务" width="500px">
      <el-form :model="revokeForm" :rules="revokeRules" ref="revokeFormRef" label-width="100px">
        <el-form-item label="撤回原因" prop="remark">
          <el-input v-model="revokeForm.remark" type="textarea" placeholder="请输入撤回原因" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="revokeForm.userId" placeholder="请输入用户ID" type="number" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="revokeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRevokeSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog v-model="viewDialogVisible" title="任务详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务ID">{{ viewData.task?.id }}</el-descriptions-item>
        <el-descriptions-item label="流程ID">{{ viewData.task?.processId }}</el-descriptions-item>
        <el-descriptions-item label="节点ID">{{ viewData.task?.nodeId }}</el-descriptions-item>
        <el-descriptions-item label="单据类型">
          <el-tag v-if="viewData.task?.billType === 'production_task'" type="success">生产任务</el-tag>
          <el-tag v-else-if="viewData.task?.billType === 'purchase_order'" type="warning">采购订单</el-tag>
          <el-tag v-else-if="viewData.task?.billType === 'finance_bill'" type="danger">财务单据</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="单据ID">{{ viewData.task?.billId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="viewData.task?.status === 0" type="warning">待办</el-tag>
          <el-tag v-else-if="viewData.task?.status === 1" type="success">已办</el-tag>
          <el-tag v-else-if="viewData.task?.status === 2" type="info">已发</el-tag>
          <el-tag v-else-if="viewData.task?.status === 3" type="danger">撤回</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人ID">{{ viewData.task?.assigneeId }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ viewData.task?.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ viewData.task?.endTime }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ viewData.task?.remark }}</el-descriptions-item>
      </el-descriptions>

      <div class="history-list">
        <h4>操作历史</h4>
        <el-table :data="viewData.history" border>
          <el-table-column prop="action" label="操作" />
          <el-table-column prop="userId" label="操作人ID" />
          <el-table-column prop="actionTime" label="操作时间" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { workflowTaskApi } from '@/api/production/workflow'

// 响应式数据
const loading = ref(false)
const startDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const revokeDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const startFormRef = ref()
const approveFormRef = ref()
const revokeFormRef = ref()

// 搜索表单
const searchForm = reactive({
  billType: '',
  status: null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 启动表单
const startForm = reactive({
  processId: null,
  billType: '',
  billId: null,
  userId: null
})

// 审批表单
const approveForm = reactive({
  taskId: null,
  action: 'approve',
  remark: '',
  userId: null
})

// 撤回表单
const revokeForm = reactive({
  taskId: null,
  remark: '',
  userId: null
})

// 查看数据
const viewData = reactive({
  task: null,
  history: []
})

// 表单验证规则
const startRules = {
  processId: [
    { required: true, message: '请输入流程ID', trigger: 'blur' }
  ],
  billType: [
    { required: true, message: '请选择单据类型', trigger: 'change' }
  ],
  billId: [
    { required: true, message: '请输入单据ID', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入启动人ID', trigger: 'blur' }
  ]
}

const approveRules = {
  action: [
    { required: true, message: '请选择操作类型', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入审批意见', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ]
}

const revokeRules = {
  remark: [
    { required: true, message: '请输入撤回原因', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ]
}

// 获取数据
const getData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    console.log('请求参数:', params)
    const response = await workflowTaskApi.list(params)
    console.log('API返回数据:', response)

    // 检查返回数据的结构
    if (response && response.records) {
      // 直接使用返回的数据（MyBatis-Plus分页格式）
      console.log('处理后的数据:', response)
      console.log('记录列表:', response.records)
      console.log('总记录数:', response.total)
      tableData.value = response.records || []
      pagination.total = response.total || 0
      pagination.current = response.current || 1
      pagination.size = response.size || 10
    } else if (response && response.code === 200 && response.data) {
      // 标准API响应格式
      console.log('处理后的数据:', response)
      console.log('记录列表:', response.data.records)
      console.log('总记录数:', response.data.total)
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.current = response.data.current || 1
      pagination.size = response.data.size || 10
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    billType: '',
    status: null
  })
  handleSearch()
}

// 获取当前用户信息
const getCurrentUser = () => {
  try {
    const username = localStorage.getItem('username')
    return username ? { username } : null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 启动工作流
const handleStartWorkflow = () => {
  const currentUser = getCurrentUser()
  Object.assign(startForm, {
    processId: null,
    billType: '',
    billId: null,
    userId: currentUser ? currentUser.username : null // 自动设置当前用户
  })
  startDialogVisible.value = true
}

// 启动提交
const handleStartSubmit = async () => {
  try {
    await startFormRef.value.validate()
    const response = await workflowTaskApi.start(startForm)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('工作流启动成功')
      startDialogVisible.value = false
      getData()
    } else if (response && response.success) {
      // 兼容其他响应格式
      ElMessage.success('工作流启动成功')
      startDialogVisible.value = false
      getData()
    } else {
      ElMessage.error(response?.message || '启动失败')
    }
  } catch (error) {
    console.error('启动工作流失败:', error)
    ElMessage.error('启动失败：' + (error.message || '未知错误'))
  }
}

// 审批
const handleApprove = (row) => {
  const currentUser = getCurrentUser()
  Object.assign(approveForm, {
    taskId: row.id,
    action: 'approve',
    remark: '',
    userId: currentUser ? currentUser.username : null // 自动设置当前用户
  })
  approveDialogVisible.value = true
}

// 审批提交
const handleApproveSubmit = async () => {
  try {
    await approveFormRef.value.validate()
    const response = await workflowTaskApi.approve(approveForm)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('审批成功')
      approveDialogVisible.value = false
      getData()
    } else if (response && response.success) {
      // 兼容其他响应格式
      ElMessage.success('审批成功')
      approveDialogVisible.value = false
      getData()
    } else {
      ElMessage.error(response?.message || '审批失败')
    }
  } catch (error) {
    console.error('审批失败:', error)
    ElMessage.error('审批失败：' + (error.message || '未知错误'))
  }
}

// 撤回
const handleRevoke = (row) => {
  const currentUser = getCurrentUser()
  Object.assign(revokeForm, {
    taskId: row.id,
    remark: '',
    userId: currentUser ? currentUser.username : null // 自动设置当前用户
  })
  revokeDialogVisible.value = true
}

// 撤回提交
const handleRevokeSubmit = async () => {
  try {
    await revokeFormRef.value.validate()
    const response = await workflowTaskApi.revoke(revokeForm)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('撤回成功')
      revokeDialogVisible.value = false
      getData()
    } else if (response && response.success) {
      // 兼容其他响应格式
      ElMessage.success('撤回成功')
      revokeDialogVisible.value = false
      getData()
    } else {
      ElMessage.error(response?.message || '撤回失败')
    }
  } catch (error) {
    console.error('撤回失败:', error)
    ElMessage.error('撤回失败：' + (error.message || '未知错误'))
  }
}

// 查看
const handleView = async (row) => {
  try {
    const response = await workflowTaskApi.getById(row.id)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      viewData.task = response.data.task
      viewData.history = response.data.history || []
      viewDialogVisible.value = true
    } else if (response && response.task) {
      // 直接返回任务数据的情况
      viewData.task = response.task
      viewData.history = response.history || []
      viewDialogVisible.value = true
    } else {
      ElMessage.error('获取任务详情失败')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败：' + (error.message || '未知错误'))
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  getData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getData()
}

// 初始化
onMounted(() => {
  getData()
})
</script>

<style scoped>
.workflow-task {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.history-list {
  margin-top: 20px;
}

.history-list h4 {
  margin-bottom: 10px;
}
</style>
